﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;

namespace Mindfor.Web
{
	/// <summary>
	/// Specifies that string data field can contains only custom set of html tags.
	/// </summary>
	public class AllowHtmlTagsAttribute : ValidationAttribute
	{
		/// <summary>
		/// Gets list of allowed html tags. Other will throw error message.
		/// </summary>
		public List<string> AllowedTags { get; private set; }

		/// <summary>
		/// Initializes new instance.
		/// </summary>
		/// <param name="allowedTags">List of allowed html tags. Other will throw error message.</param>
		public AllowHtmlTagsAttribute(params string[] allowedTags)
		{
			AllowedTags = new List<string>(allowedTags);
		}

		/// <summary>
		/// Determines whether the specified value of the object is valid.
		/// </summary>
		/// <param name="value">The value of the object to validate.</param>
		/// <returns>true if the specified value is valid; otherwise, false.</returns>
		public override bool IsValid(object value)
		{
			// convert to string
			string s = value.ToString();

			// convert tags to lower
			string[] allowed = new string[AllowedTags.Count];
			for (int i=0; i<AllowedTags.Count; i++)
				allowed[i] = AllowedTags[i].ToLower();
			
			// find html tags
			string pattern = @"</?(?<tag>\w+)[^>]*>";
			Regex regex = new Regex(pattern);
			foreach (Match match in regex.Matches(s))
			{
				string tag = match.Groups["tag"].Value.ToLower();
				if (!allowed.Contains(tag))
					return false;
			}

			return true;
		}
	}
}
